package com.doria.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.doria.common.ad_enum.CodeEnum;
import com.doria.common.ad_enum.MsgEnum;
import com.doria.common.pojo.vo.HttpResult;
import org.aspectj.apache.bcel.classfile.Code;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.Random;

@Configuration
public class MyTestFilter implements GlobalFilter, Ordered {


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("全局过滤器执行");
        ServerHttpResponse response = exchange.getResponse();

        int i = new Random().nextInt(2);
        if (i==0){
            // 执行放行
            return chain.filter(exchange);
        }else {
            // 拦截
            return getVoidMon(response,false, CodeEnum.PERMISSIONS_ERROR,MsgEnum.PERMISSIONS_ERROR);
        }

    }

    @Override
    public int getOrder() {
        return 0;
    }

    /**
     * 获取一个空的事务
     * @param response
     * @return
     */
    public Mono<Void> getVoidMon(ServerHttpResponse response,Boolean flag, CodeEnum codeEnum, MsgEnum msgEnum){
        // 配置响应头
        response.getHeaders().add("Content-type","application/json;charset=UTF-8");
        // 配置响应体
        HttpResult httpResult = new HttpResult(flag,codeEnum,msgEnum);
        // 开始蜜汁操作，看不懂了
        DataBuffer dbf = response.bufferFactory().wrap(
                JSON.toJSONString(httpResult).getBytes());
        return response.writeWith(Flux.just(dbf));
    }
}
